<template>
  <view class="pages">
    <u-sticky class="sticky_c" offsetTop="0" :style="{ 'background-Color': '#F6F6F6' }">
      <view :style="{ height: statusHeight + 'rpx' }"></view>
      <uni-search-bar
        @confirm="search"
        :focus="isFocus"
        v-model="searchValue"
        @blur="blur"
        @focus="focus"
        radius="18"
        @input="input"
        @cancel="cancel"
        @clear="clear"
        bgColor="#fff"
      >
      </uni-search-bar>
    </u-sticky>
    <view v-if="!searchValue" class="tip_text">快速搜索聊天内容</view>
    <view
      class="clear_msg"
      @click="popupShow = true"
      v-if="!searchValue"
      :style="{ bottom: keyHeight + 'px' }"
    >
      清空所有聊天记录
    </view>
    <view
      v-if="searchValue"
      class="search_box"
      :style="{
        height: `calc(100vh - ${topHeight + 'rpx'})`,
      }"
    >
      <view
        @click="onSearch"
        v-if="!goSearch"
        :style="{ color: transaction_type.value == 1 ? '#562bff' : '#54CEAB' }"
        class="search_text"
        >搜索:“{{ searchValue }}”</view
      >
      <view
        class="msg_list"
        :style="{
          height: `calc(100vh - ${topHeight + 'rpx'})`,
        }"
        v-else
      >
        <view
          class="no-content"
          v-if="searchValue && chartList.length == 0 && finish == true && goSearch"
        >
          <image src="@/static/pregnancy/no_pre.png" mode="scaleToFill"></image>
          <view class="no-text">没有查找到相关记录</view>
        </view>
        <scroll-view
          v-else
          scroll-y
          :lower-threshold="200"
          @scrolltolower="more"
          :scroll="true"
          :style="{
            height: `calc(100vh - ${topHeight + 'rpx'})`,
          }"
        >
          <view
            class="msg_item"
            v-for="(item, index) of chartList"
            :key="index"
            @click.stop="gobackmsg(item?.content?.ID)"
          >
            <view class="left">
              <image
                :src="item?.uuid?.split('_')[0] == item?.uid ? item?.avatar : item?.to_avatar"
                mode="scaleToFill"
              />
            </view>
            <view class="right">
              <view class="top">
                <view class="top_left">{{ item?.nickname }}</view>
                <view class="top_right">{{ item?.create_time }}</view>
              </view>
              <view
                class="bottom"
                v-html="highlightSearchText(item?.content?.payload?.text)"
              ></view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
  <h-modal
    @clear="popupShow = false"
    :show="popupShow"
    @bind="confirmClear"
    titlea="聊天记录删除后无法恢复"
    text="是否确认删除"
    leftBtn="取消"
    rightBtn="确认"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onReady, onPageScroll, onShow, onReachBottom, onHide } from '@dcloudio/uni-app' // 该方法只能用在父组件内，子组件内不生效
import { getChatLogList, delAllList } from '@/api/pregnancy/index'
import { useMemberStore, useSystemStore } from '@/stores'
const finish = ref(false) // 是否加载完所有聊天记录
const chartList = ref([]) // 聊天记录列表
const params = ref({
  page: 1,
  limit: 10,
  uid: '', //用户UID
  to_uid: '', //接收人UID
  keyword: '',
  transaction_type: '',
})
const doctor_uid = ref('') //医生UID
function filterRecordsByText(searchText) {
  // 使用filter方法过滤出包含搜索词的记录
  return chartList.value.filter((record) => {
    return record?.content?.payload?.text?.includes(searchValue.value) // 假设每条记录有一个content字段存储聊天内容
  })
}
// 获取聊天记录列表
async function getChatLog() {
  const userStore = useMemberStore()
  params.value.uid = userStore.userInfo.id //用户UID
  params.value.to_uid = doctor_uid.value //接收人UID
  params.value.transaction_type = transaction_type.value //接收人UID
  // params.value.uid = 1499 //用户UID
  // params.value.to_uid = 499 //接收人UID
  params.value.keyword = searchValue.value
  const res = await getChatLogList(params.value)
  chartList.value = res.data.data.map((item: any) => {
    console.log(JSON.parse(item.content))
    item.content = JSON.parse(item.content)
    return item
  })
  // chartList.value = filterRecordsByText(searchValue.value)
  if (res.data.data.length == 0) {
    finish.value = true
  } else {
    finish.value = false
  }
}
function navigateTo(url: any) {
  uni.navigateTo({
    url,
  })
}
function highlightSearchText(text: string) {
  const query = searchValue.value.trim()
  if (query) {
    const regex = new RegExp(query, 'gi')
    // 少时诵诗书试试神经病
    return text?.replace(
      regex,
      (matchedText) =>
        `<span class="highlight" style="color:${
          transaction_type.value == 1 ? '#562bff' : '#54CEAB'
        }">${matchedText}</span>`,
    )
  }
  return text
}
// 获取高度
const topHeight = ref(0)
const popupShow = ref(false)
function getDocumentInfo() {
  const query = uni.createSelectorQuery()
  query
    ?.select('.u-sticky')
    ?.boundingClientRect((data: any) => {
      topHeight.value = Math.floor(data?.height) * 2
      console.log(Math.floor(data?.height) * 2)
    })
    .exec()
}
const os = ref()
const systemKey = ref()
uni.getSystemInfo({
  success: (e) => {
    os.value = e.osName
    systemKey.value = e.screenHeight - e.windowHeight
    console.log(systemKey.value)
  },
})
const keyHeight = ref(0)
const isFocus = ref(false)
function listener(res: any) {
  if (res.height) {
    keyHeight.value = res.height
  } else {
    keyHeight.value = 0
  }
}

const doctorAvatar = ref('')
const nickname = ref('')
const doc_id = ref('')
const transaction_type = ref()
onLoad((options: any) => {
  transaction_type.value = options?.chat_type
  console.log('options', options)
  doctor_uid.value = options?.id
  doc_id.value = options?.doctor_id
  // delParams.value.to_uid = options?.id
  delParams.value.uid = options?.id
  doctorAvatar.value = options?.avatar
  nickname.value = options?.nickname
  getSystemInfo()
  getChatLog()
})
onShow(() => {
  isFocus.value = true
  // #ifdef APP-PLUS || APP-IOS
  uni.onKeyboardHeightChange(listener)
  // #endif
})
onReady(() => {
  getDocumentInfo()
})
onPageScroll(() => {
  if (isFocus.value) {
    isFocus.value = false
    uni.hideKeyboard()
  }
})
onReachBottom(() => {
  params.value.page++
  getChatLog()
})

onHide(() => {
  // #ifdef APP-PLUS || APP-IOS
  uni.offKeyboardHeightChange(listener)
  // #endif
})

/**
 * 获取系统信息
 */
const statusHeight = ref(0)
function getSystemInfo() {
  uni.getSystemInfo({
    success: (e) => {
      statusHeight.value = e.statusBarHeight * 2
    },
  })
}
const searchValue = ref()
// 搜素
function search() {
  console.log('search')
  goSearch.value = true
  getChatLog()
}
function gobackmsg(id) {
  uni.$emit('goback', id)
  uni.navigateBack()
}
// 失去焦点
function blur() {
  isFocus.value = false
  uni.hideKeyboard()
}
// 获取焦点
function focus() {
  isFocus.value = true
}
// 输入框变化
function input() {
  chartList.value = []
  goSearch.value = false
}
// 取消
function cancel() {
  uni.navigateBack()
}
// 清除
function clear() {
  searchValue.value = ''
}

const delParams = ref({
  uid: '',
  transaction_type: 0,
})
const setMsgList = ref({})
setMsgList.value = uni.getStorageSync('chatMsgList') || {}

// 确定清楚
function confirmClear() {
  console.log('confirmClear')
    delParams.value.transaction_type = transaction_type.value
    const res = delAllList(delParams.value)
    popupShow.value = false
    // uni.setStorageSync(doc_id.value, [])
    setMsgList.value[doc_id.value] = []
    uni.setStorageSync('chatMsgList', setMsgList.value)
    uni.$emit('clearall', doc_id.value)
 
}

// 去搜索
const goSearch = ref(false)
function onSearch() {
  goSearch.value = true
  search()
}
const total = ref()
const finished = ref(false)
const list = ref()
function more() {
  console.log('--------出低了')
}
</script>

<style lang="scss" scoped>
.pages {
  display: flex;
  flex-direction: column;
  .search_box {
    background-color: #fff;
    .search_text {
      margin: 0 27rpx;
      padding: 20rpx 0 13rpx 32rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 24rpx;
      color: #562bff;
      border-bottom: 1rpx solid #e6e6e6;
    }
    .msg_list {
      display: flex;
      flex-direction: column;
      .msg_item {
        padding: 20rpx 0 21rpx 0;
        margin: 0 27rpx;

        border-bottom: 1rpx solid #e6e6e6;
        background-color: #fff;
        display: flex;
        align-items: center;
        .left {
          width: 59rpx;
          height: 59rpx;
          border-radius: 6rpx 6rpx 6rpx 6rpx;
          margin-left: 16rpx;
          image {
            width: 59rpx;
            height: 59rpx;
          }
        }
        .right {
          flex: 1;
          display: flex;
          flex-direction: column;
          margin-left: 16rpx;
          .top {
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 20rpx;
            color: #6b6b6b;
            display: flex;
            align-items: center;
            justify-content: space-between;
          }
          .bottom {
            flex: 1;
            margin-right: 10rpx;
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 22rpx;
            color: #000000;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
          }
        }
      }
    }
  }
  .tip_text {
    margin-top: 28rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 24rpx;
    color: #999999;
    text-align: center;
  }
  .clear_msg {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    height: 99rpx;
    line-height: 99rpx;
    text-align: center;
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 26rpx;
    color: #333333;
    background: #ffffff;
    transition: all 0.3;
  }
}
.highlight {
  color: #562bff;
}
.no-content {
  text-align: center;
  padding-top: 200rpx;
  image {
    width: 226rpx;
    height: 204rpx;
  }
  .no-text {
    margin-top: 55rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 22rpx;
    color: #666666;
  }
}
::v-deep .u-sticky {
  top: 0 !important;
}
// ::v-deep .uni-searchbar__box {
// }
::v-deep .uni-searchbar__box-search-input {
  font-family: PingFang SC, PingFang SC;
  font-weight: 500 !important;
  font-size: 26rpx !important;
  color: #333333 !important;
}
::v-deep .uni-searchbar__cancel {
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 30rpx;
  color: #00c1b9;
}
</style>
<style lang="scss">
page {
  background-color: #f6f6f6;
  min-height: 100vh;
}
</style>
